import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;

import javax.swing.BorderFactory;
import javax.swing.ButtonModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

public class AdminStudentPanel extends JPanel{
       
        JLabel fn=new JLabel("First Name: ");
    JLabel ln=new JLabel("Last Name: ");
    JLabel id=new JLabel("ID #: ");
    JTextField fntext=new JTextField(10);
    JTextField lntext=new JTextField(10);
    JTextField idtext=new JTextField(10);
        JPanel panel = new JPanel();
        JPanel panelt = new JPanel();
        JPanel panelc = new JPanel();
        JPanel panelc1 = new JPanel();
        JPanel panelc2 = new JPanel();
        JPanel panelb = new JPanel();
        JButton delete=new JButton();
        JButton home=new JButton();
        JButton add=new JButton();
        JButton search=new JButton();
        JButton reset = new JButton();
        JTable table;
        JTable table2;
        String[] cols={"Delete", "First Name", "Last Name", "ID Number"};
        String[] cols2={"First Name", "Last Name", "ID Number", "Major"};
        Boolean j=false;
        Object data[][]={
                                        };
        Object data2[][]={{"","","",""},
                                        {"","","",""},
                                        {"","","",""},
                                        {"","","",""},
                                        {"","","",""}};
        //Object data3[][]={{"","",""}};
//        DefaultTableModel model = new DefaultTableModel(null, cols){
//        public Class getColumnClass(int c) {
//            switch (c) {
//              case 0: return Boolean.class;
//              default: return String.class;
//            }  
//        }
//        };
//        
        DefaultTableModel model2 = new DefaultTableModel(null, cols2){};
        DefaultTableModel dtm,dtm2;
        int row=0,row2=0;
        Image img;
        
        public void searchActionPerformed(ActionEvent e) {
                String s_fn = fntext.getText();
                String s_ln = lntext.getText();
                String s_id = idtext.getText();
                
                // Clear the table
                //while (row>0) {dtm.removeRow(row-1); row--;}
                for(int i =0; i<dtm.getRowCount(); i++){
                                    dtm.removeRow(i);
                                    i--;  
            	}
                
                try{
                String dName = "com.mysql.jdbc.Driver";
                String url = "jdbc:mysql://db4free.net:3306/studentreg14?user=studentreg14&password=KCTSkcts";
                Connection con = DriverManager.getConnection(url);
                java.sql.Statement mysqlStatement = con.createStatement();
                java.sql.ResultSet resultSet = mysqlStatement.executeQuery("SELECT fname,lname,student_id FROM student_list WHERE (fname='"+s_fn+"') OR (lname='"+s_ln+"') OR (student_id='"+s_id+"')");
               
                while (resultSet.next()) {
                        row+=1;
                        String fname=resultSet.getString(1);
                        String lname=resultSet.getString(2);
                        String student_id=resultSet.getString(3);
                        Object[] program={j,fname,lname,student_id};
                        dtm.addRow(program);
                }
                con.close();
                }
                catch(Exception ex){}
                
        }
        
        public void resetActionPerformed(ActionEvent e){
        	for(int i =0; i<dtm.getRowCount(); i++){
                dtm.removeRow(i);
                i--;  
}
                
                try{
                String dName = "com.mysql.jdbc.Driver";
                String url = "jdbc:mysql://db4free.net:3306/studentreg14?user=studentreg14&password=KCTSkcts";
                Connection con = DriverManager.getConnection(url);
                java.sql.Statement mysqlStatement = con.createStatement();
                java.sql.ResultSet resultSet = mysqlStatement.executeQuery("SELECT fname,lname,student_id FROM student_list WHERE SID!=-1");
               
                while (resultSet.next()) {
                        row+=1;
                        String fname=resultSet.getString(1);
                        String lname=resultSet.getString(2);
                        String student_id=resultSet.getString(3);
                        Object[] program={j,fname,lname,student_id};
                        dtm.addRow(program);
                }
                con.close();
                }
                catch(Exception ex){}
        }
        
        public AdminStudentPanel(){
        	final ImageIcon re=new ImageIcon("reset_button.png");
     		final ImageIcon cre=new ImageIcon("reset_cbutton.png");
     		final ImageIcon se=new ImageIcon("search_button.png");
     		final ImageIcon cse=new ImageIcon("search_cbutton.png");
     		button(search,se);
     		button(reset,re);
     		
                        search.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                        searchActionPerformed(e);
                }
                        });
                        
                        search.setContentAreaFilled(false);
                        search.setIcon(se);
                        search.setRolloverIcon(cse);
                        search.setPressedIcon(cse);
                        search.getModel().addChangeListener(new ChangeListener() {
                		        @Override
                		        public void stateChanged(ChangeEvent e) {
                		            ButtonModel model = (ButtonModel) e.getSource();
                		            if (model.isRollover()) {
                		            	search.setIcon(cse);
                		            } else {
                		            	search.setIcon(se);
                		            }// etc ...//  if (model.isPressed()) {
                		         }
                		    });
                        
                        reset.addActionListener(new ActionListener(){
                                public void actionPerformed(ActionEvent e){
                                        resetActionPerformed(e);
                                }
                        });
                        
                        reset.setContentAreaFilled(false);
                        reset.setIcon(re);
                        reset.setRolloverIcon(cre);
                        reset.setPressedIcon(cre);
                        reset.getModel().addChangeListener(new ChangeListener() {
                		        @Override
                		        public void stateChanged(ChangeEvent e) {
                		            ButtonModel model = (ButtonModel) e.getSource();
                		            if (model.isRollover()) {
                		            	reset.setIcon(cre);
                		            } else {
                		            	reset.setIcon(re);
                		            }// etc ...//  if (model.isPressed()) {
                		         }
                		    });
               
                img=new ImageIcon("admin_student_background.png").getImage();
                setOpaque(false);
               
                setLayout(new BorderLayout());
                add(panel,BorderLayout.PAGE_START);
                panel.setOpaque(false);
               
                panel.setBackground(Color.WHITE);
                add(panel, BorderLayout.NORTH);
                panel.setPreferredSize(new Dimension(600,400));
               
               
                //-----TOP PANEL--------
                panelt.setBorder(BorderFactory.createTitledBorder("Search Student:"));
                //would like to allow admin to search through db to quickly find student
                //just an idea, ill add code to implement this later if i can
                panelt.setBackground(Color.WHITE);
        panelt.setPreferredSize(new Dimension(600,80));
        panelt.add(fn);
                panelt.add(fntext);
                panelt.add(ln);
                panelt.add(lntext);
                panelt.add(id);
                panelt.add(idtext);
                panelt.add(search);
                panelt.add(reset);
                panel.add(panelt, BorderLayout.NORTH);
       
       
        //-----CENTER PANEL-----
        panelc.setBackground(Color.WHITE);
        panelc.setLayout(new BorderLayout());
        panelc.setPreferredSize(new Dimension(600,270));
       
        panelc1.setBackground(Color.WHITE);
        panelc1.setLayout(new BorderLayout());
        panelc.setBorder(BorderFactory.createTitledBorder("Remove/Edit Student:"));
       
        initialize();
//        
//        model.addRow(data[0]);
//        model.addRow(data[1]);
//        model.addRow(data[2]);
//        model.addRow(data[3]);
//        model.addRow(data[4]);
//        model.addRow(data[5]);
//        model.addRow(data[6]);
//        model.addRow(data[7]);
//        model.addRow(data[8]);
//        model.addRow(data[9]);
       
//        table = new JTable(model){
//                public boolean isCellEditable(int row, int cols) {return true;}
//                
//        };
       
        TableColumn column0;
        column0 = table.getColumnModel().getColumn(0);
        column0.setPreferredWidth(25);
               
                TableColumn column1;
        column1 = table.getColumnModel().getColumn(1);
        column1.setPreferredWidth(60);
       
        TableColumn column2;
        column2 = table.getColumnModel().getColumn(2);
        column2.setPreferredWidth(60);
       
        TableColumn column3;
        column3 = table.getColumnModel().getColumn(3);
        column3.setPreferredWidth(60);
       
        table.setFillsViewportHeight(true);
        JScrollPane j1 = new JScrollPane(table);
                j1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
               
                panelc1.setPreferredSize(new Dimension(600,120));
                panelc1.add(delete, BorderLayout.SOUTH);
                panelc1.add(j1, BorderLayout.CENTER);
                panelc.add(panelc1, BorderLayout.NORTH);
               
               
               
                panelc2.setBackground(Color.WHITE);
                panelc2.setPreferredSize(new Dimension(600,50));
                panelc2.setLayout(new BorderLayout());
                panelc2.setBorder(BorderFactory.createTitledBorder("Add Student:"));
               
               
                model2.addRow(data2[0]);
        model2.addRow(data2[1]);
        model2.addRow(data2[2]);
        model2.addRow(data2[3]);
        model2.addRow(data2[4]);
     
       
        table2 = new JTable(model2){
                public boolean isCellEditable(int row, int cols) {return true;}
               
        };
       
        TableColumn column00;
        column00 = table2.getColumnModel().getColumn(0);
        column00.setPreferredWidth(25);
               
                TableColumn column11;
        column11 = table2.getColumnModel().getColumn(1);
        column11.setPreferredWidth(60);
       
        TableColumn column22;
        column22 = table2.getColumnModel().getColumn(2);
        column22.setPreferredWidth(60);
       
       
        table2.setFillsViewportHeight(true);
        JScrollPane j2 = new JScrollPane(table2);
                j2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
               
                panelc2.add(add, BorderLayout.SOUTH);
                panelc2.add(j2, BorderLayout.CENTER);
                panelc.add(panelc2, BorderLayout.CENTER);
                panel.add(panelc, BorderLayout.CENTER);
               
               
               
                //----BASE----
                panelb.setBackground(Color.WHITE);
                //panelb.setPreferredSize(new Dimension(600,20));
                panelb.setLayout(new BorderLayout());
                panelb.add(home, BorderLayout.EAST);
                panel.add(panelb, BorderLayout.SOUTH);
                add(panel, BorderLayout.PAGE_START);
                panelb.setOpaque(false);
                
                final ImageIcon ho=new ImageIcon("home_button.png");
        		final ImageIcon cho=new ImageIcon("home_cbutton.png");
        		final ImageIcon ad=new ImageIcon("add_button.png");
        		final ImageIcon cad=new ImageIcon("add_cbutton.png");
        		final ImageIcon de=new ImageIcon("delete_button.png");
        		final ImageIcon cde=new ImageIcon("delete_cbutton.png");
        		button(home,ho);
        		button(add,ad);
        		button(delete,de);
       
                home.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
               
                remove(panel);
                add(new AdminMenuPanel(), BorderLayout.PAGE_START);
                validate();
                repaint();
               
            }
    });
                home.setContentAreaFilled(false);
                home.setIcon(ho);
                home.setRolloverIcon(cho);
                home.setPressedIcon(cho);
                home.getModel().addChangeListener(new ChangeListener() {
        		        @Override
        		        public void stateChanged(ChangeEvent e) {
        		            ButtonModel model = (ButtonModel) e.getSource();
        		            if (model.isRollover()) {
        		            	home.setIcon(cho);
        		            } else {
        		            	home.setIcon(ho);
        		            }// etc ...//  if (model.isPressed()) {
        		         }
        		    });
               
                delete.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                 
                //int c = row;
                for(int i =0; i<dtm.getRowCount(); i++){
                        String s = (String) table.getModel().getValueAt(i, 3);
                        Boolean b = (Boolean) table.getModel().getValueAt(i, 0);
                        //System.out.println(b);
                        if(b==true)
                                {
                                        dtm.removeRow(i);
                                        delete(s);
                                        i--;
                                }
                       
                }
            }
    });
                delete.setContentAreaFilled(false);
                delete.setIcon(de);
                delete.setRolloverIcon(cde);
                delete.setPressedIcon(cde);
                delete.getModel().addChangeListener(new ChangeListener() {
        		        @Override
        		        public void stateChanged(ChangeEvent e) {
        		            ButtonModel model = (ButtonModel) e.getSource();
        		            if (model.isRollover()) {
        		            	delete.setIcon(cde);
        		            } else {
        		            	delete.setIcon(de);
        		            }// etc ...//  if (model.isPressed()) {
        		         }
        		    });
               
                add.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                 
               
                for(int i =0; i<model2.getRowCount(); i++){
                       
                        String fnn = (String) table2.getModel().getValueAt(i, 0);
                        String lnn = (String) table2.getModel().getValueAt(i, 1);
                        String idd = (String) table2.getModel().getValueAt(i,2);
                        String mj = (String) table2.getModel().getValueAt(i,3);
                        System.out.println(fnn + " " + lnn + " " + idd);
                        if(fnn!=""&&lnn!=""&&idd!="")
                                {
                                       
                                                dtm.addRow(new Object[]{j, fnn, lnn, idd});
                                        add(fnn,lnn,idd,mj);
                                        
                                }
                       
                }
                for(int j=0;j<model2.getRowCount();j++){
                	model2.removeRow(0);//need to get the rows modified!!
                	model2.addRow(new Object[]{"","","",""});
                }
            }
    });
                add.setContentAreaFilled(false);
                add.setIcon(ad);
                add.setRolloverIcon(cad);
                add.setPressedIcon(cad);
                add.getModel().addChangeListener(new ChangeListener() {
        		        @Override
        		        public void stateChanged(ChangeEvent e) {
        		            ButtonModel model = (ButtonModel) e.getSource();
        		            if (model.isRollover()) {
        		            	add.setIcon(cad);
        		            } else {
        		            	add.setIcon(ad);
        		            }// etc ...//  if (model.isPressed()) {
        		         }
        		    });
        }
       
       
        private void initialize(){
                //available courses
                dtm=new DefaultTableModel(data,cols){
                        public Class getColumnClass(int c) {
                    switch (c) {
                      case 0: return Boolean.class;
                      default: return String.class;
                    }  
                }
                         @Override
               public boolean isCellEditable(int row, int col) {
                    switch (col) {
                        case 0:
                            return true;
                        default:
                            return false;
                     }
               }
               
                };
                table=new JTable(dtm);
                //int row=0;
               
                try{
                        String dName = "com.mysql.jdbc.Driver";
                        String url = "jdbc:mysql://db4free.net:3306/studentreg14?user=studentreg14&password=KCTSkcts";
                        Connection con = DriverManager.getConnection(url);
                        java.sql.Statement mysqlStatement = con.createStatement();
                        java.sql.ResultSet resultSet = mysqlStatement.executeQuery("SELECT fname,lname,student_id FROM student_list WHERE SID!=-1");
                       
                        while (resultSet.next()) {
                                row+=1;
                                String fname=resultSet.getString(1);
                                String lname=resultSet.getString(2);
                                String student_id=resultSet.getString(3);
                                Object[] program={j,fname,lname,student_id};
                                dtm.addRow(program);
                                System.out.println("student added");
                        }
                        con.close();
                        }
                        catch(Exception ex){}
               
               
        }
       
        private void delete(String s){
                try{
                        String dName = "com.mysql.jdbc.Driver";
                        String url = "jdbc:mysql://db4free.net:3306/studentreg14?user=studentreg14&password=KCTSkcts";
                        Connection con = DriverManager.getConnection(url);
                        java.sql.Statement mysqlStatement = con.createStatement();
                        mysqlStatement.executeUpdate("DELETE FROM student_list WHERE student_id ='"+s+"'");
                        System.out.println(s+" "+"dropped?");
                        con.close();
                        }
                        catch(Exception ex){}
        }
       
        private void add(String fname,String lname,String sid,String major){
                row+=3;
        ////*******must have different sid num(=row) from the ones in db!!!!!!!********////
                try{
                        String dName = "com.mysql.jdbc.Driver";
                        String url = "jdbc:mysql://db4free.net:3306/studentreg14?user=studentreg14&password=KCTSkcts";
                        Connection con = DriverManager.getConnection(url);
                        java.sql.Statement mysqlStatement = con.createStatement();
                        java.sql.ResultSet resultSet = mysqlStatement.executeQuery("SELECT COUNT(*) FROM student_list WHERE SID='"+sid+"'");
                       
                        while (resultSet.next()) {
                                int osid=resultSet.getInt(1);
                                if(osid!=0){
                                        System.out.println("student already exists");
                                }
                                else{
                                        try{
                                                row+=1;
                                                String dName2 = "com.mysql.jdbc.Driver";
                                                String url2 = "jdbc:mysql://db4free.net:3306/studentreg14?user=studentreg14&password=KCTSkcts";
                                                Connection con2 = DriverManager.getConnection(url2);
                                                java.sql.Statement mysqlStatement2 = con2.createStatement();
                                                mysqlStatement2.executeUpdate("INSERT INTO student_list VALUES ('"+row+"','temp','temp','"+fname+"','"+lname+"','"+major+"','"+sid+"')");
                                                System.out.println("new student inserted into student list");
                                               
                                                con2.close();
                                                }
                                                catch(Exception ex){}
                                }
                        }
                        con.close();
                        }
                        catch(Exception ex){}
        }
       
        @Override
        public void paintComponent(Graphics g) {
                super.paintComponents(g);
            g.drawImage(img, 0, 0, this);
        }
       
        private void button(JButton b, ImageIcon i){
                b.setBorderPainted(false);
                b.setBorder(null);
                //button.setFocusable(false);
                b.setMargin(new Insets(0, 0, 0, 0));
                b.setContentAreaFilled(false);
                b.setIcon(i);
                //b.setRolloverIcon(myIcon2);
                //b.setPressedIcon(myIcon3);
        }
       
}